<template>
  <div class="sales-chart-container">
    <div class="chart-header">
      <h3 class="chart-title">{{ title }}</h3>
      <div class="time-range-selector">
        <button 
          v-for="range in timeRanges" 
          :key="range.value" 
          :class="['range-btn', { active: selectedRange === range.value }]"
          @click="changeTimeRange(range.value)"
        >
          {{ range.label }}
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载数据中...</p>
    </div>
    
    <div v-else-if="error" class="error-container">
      <i class="fas fa-exclamation-triangle"></i>
      <p>{{ error }}</p>
    </div>
    
    <div v-else-if="!chartData.labels || chartData.labels.length === 0" class="empty-container">
      <i class="fas fa-chart-line"></i>
      <p>暂无数据</p>
    </div>
    
    <div v-else class="chart-wrapper">
      <canvas ref="chartRef"></canvas>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
import Chart from 'chart.js/auto';
import { generateDistributorSalesData } from '@/utils/agentMock';

// 定义属性
interface Props {
  distributorId: string;
  title?: string;
  showSales?: boolean;
  showOrders?: boolean;
  showCommission?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '销售数据趋势',
  showSales: true,
  showOrders: true,
  showCommission: true
});

// 状态管理
const chartRef = ref<HTMLCanvasElement | null>(null);
const chartInstance = ref<Chart | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
const salesData = ref<any[]>([]);
const selectedRange = ref<7 | 14 | 30>(30);

// 时间范围选项
const timeRanges = [
  { label: '7天', value: 7 },
  { label: '14天', value: 14 },
  { label: '30天', value: 30 }
];

// 图表数据
const chartData = computed(() => {
  if (!salesData.value || salesData.value.length === 0) {
    return { labels: [], datasets: [] };
  }
  
  // 根据选择的时间范围过滤数据
  const filteredData = salesData.value.slice(-selectedRange.value);
  
  // 准备图表数据
  const labels = filteredData.map(item => item.date);
  
  const datasets = [];
  
  if (props.showSales) {
    datasets.push({
      label: '销售额',
      data: filteredData.map(item => item.sales),
      borderColor: '#4a6cf7',
      backgroundColor: 'rgba(74, 108, 247, 0.1)',
      borderWidth: 2,
      tension: 0.4,
      yAxisID: 'y'
    });
  }
  
  if (props.showOrders) {
    datasets.push({
      label: '订单量',
      data: filteredData.map(item => item.orders),
      borderColor: '#10b981',
      backgroundColor: 'rgba(16, 185, 129, 0.1)',
      borderWidth: 2,
      tension: 0.4,
      yAxisID: 'y1'
    });
  }
  
  if (props.showCommission) {
    datasets.push({
      label: '佣金',
      data: filteredData.map(item => item.commission),
      borderColor: '#f59e0b',
      backgroundColor: 'rgba(245, 158, 11, 0.1)',
      borderWidth: 2,
      tension: 0.4,
      yAxisID: 'y'
    });
  }
  
  return { labels, datasets };
});

// 图表配置
const chartConfig = computed(() => {
  return {
    type: 'line',
    data: chartData.value,
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: {
        mode: 'index',
        intersect: false,
      },
      plugins: {
        legend: {
          position: 'top',
          labels: {
            usePointStyle: true,
            padding: 20,
            font: {
              size: 12
            }
          }
        },
        tooltip: {
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          titleColor: '#6b7280',
          bodyColor: '#1f2937',
          borderColor: '#e5e7eb',
          borderWidth: 1,
          padding: 12,
          boxPadding: 6,
          usePointStyle: true,
          callbacks: {
            label: function(context: any) {
              let label = context.dataset.label || '';
              if (label) {
                label += ': ';
              }
              if (context.parsed.y !== null) {
                if (label.includes('销售额') || label.includes('佣金')) {
                  label += '¥' + context.parsed.y.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  });
                } else {
                  label += context.parsed.y;
                }
              }
              return label;
            }
          }
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          },
          ticks: {
            font: {
              size: 12
            }
          }
        },
        y: {
          position: 'left',
          title: {
            display: true,
            text: '金额 (¥)',
            font: {
              size: 12
            }
          },
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          },
          ticks: {
            callback: function(value: any) {
              return '¥' + value.toLocaleString('zh-CN');
            },
            font: {
              size: 12
            }
          }
        },
        y1: {
          position: 'right',
          title: {
            display: true,
            text: '订单量',
            font: {
              size: 12
            }
          },
          grid: {
            drawOnChartArea: false
          },
          ticks: {
            font: {
              size: 12
            }
          }
        }
      }
    }
  };
});

// 方法
const fetchData = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    // 在实际项目中，这里应该调用API获取数据
    const data = await generateDistributorSalesData(props.distributorId, 30);
    salesData.value = data;
  } catch (err) {
    console.error('获取销售数据失败:', err);
    error.value = '获取数据失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const createChart = () => {
  if (!chartRef.value) return;
  
  // 销毁旧图表实例（如果存在）
  if (chartInstance.value) {
    chartInstance.value.destroy();
  }
  
  // 创建新图表
  const ctx = chartRef.value.getContext('2d');
  if (ctx) {
    chartInstance.value = new Chart(ctx, chartConfig.value);
  }
};

const updateChart = () => {
  if (chartInstance.value) {
    chartInstance.value.data = chartData.value;
    chartInstance.value.update();
  }
};

const changeTimeRange = (days: 7 | 14 | 30) => {
  selectedRange.value = days;
};

// 生命周期钩子
onMounted(async () => {
  await fetchData();
  createChart();
});

// 销毁图表实例
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.destroy();
  }
});

// 监听数据变化，更新图表
watch(chartData, () => {
  updateChart();
}, { deep: true });

// 监听属性变化，重新获取数据
watch(() => props.distributorId, () => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.sales-chart-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 24px;
  
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .chart-title {
      margin: 0;
      font-size: 18px;
      color: #1f2937;
      font-weight: 600;
    }
    
    .time-range-selector {
      display: flex;
      border-radius: 8px;
      overflow: hidden;
      border: 1px solid #e5e7eb;
      
      .range-btn {
        background: none;
        border: none;
        padding: 6px 12px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s;
        color: #6b7280;
        
        &:not(:last-child) {
          border-right: 1px solid #e5e7eb;
        }
        
        &:hover:not(.active) {
          background-color: #f9fafb;
        }
        
        &.active {
          background-color: #4a6cf7;
          color: white;
        }
      }
    }
  }
  
  .chart-wrapper {
    position: relative;
    height: 350px;
  }
  
  .loading-container,
  .error-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 350px;
    
    i {
      font-size: 32px;
      margin-bottom: 16px;
      color: #9ca3af;
    }
    
    p {
      color: #6b7280;
      font-size: 14px;
    }
  }
  
  .loading-container {
    .spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(74, 108, 247, 0.2);
      border-top-color: #4a6cf7;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }
    
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
  }
  
  .error-container {
    i {
      color: #ef4444;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sales-chart-container {
    padding: 16px;
    
    .chart-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      margin-bottom: 16px;
    }
    
    .chart-wrapper {
      height: 300px;
    }
  }
}
</style> 